use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::{Duration, Instant};
use rayon::prelude::*;
use tokio::time::sleep;

/// 系统级软件demo - 展示Rust在系统编程中的优势
/// 包括：内存安全、零成本抽象、并发安全、性能优化

// 自定义内存池 - 展示Rust的内存管理能力
struct MemoryPool {
    blocks: Vec<Vec<u8>>,
    available: Arc<Mutex<Vec<usize>>>,
}

impl MemoryPool {
    fn new(block_size: usize, num_blocks: usize) -> Self {
        let mut blocks = Vec::with_capacity(num_blocks);
        let mut available = Vec::with_capacity(num_blocks);
        
        for i in 0..num_blocks {
            blocks.push(vec![0u8; block_size]);
            available.push(i);
        }
        
        Self {
            blocks,
            available: Arc::new(Mutex::new(available)),
        }
    }
    
    fn allocate(&self) -> Option<usize> {
        let mut available = self.available.lock().unwrap();
        available.pop()
    }
    
    fn deallocate(&self, index: usize) {
        let mut available = self.available.lock().unwrap();
        available.push(index);
    }
    
    fn get_block(&self, index: usize) -> Option<&[u8]> {
        self.blocks.get(index).map(|v| v.as_slice())
    }
}

// 高性能数据结构 - 展示Rust的零成本抽象
#[derive(Debug, Clone)]
struct SystemMetrics {
    cpu_usage: f64,
    memory_usage: f64,
    network_io: u64,
    disk_io: u64,
    timestamp: Instant,
}

impl SystemMetrics {
    fn new() -> Self {
        Self {
            cpu_usage: 0.0,
            memory_usage: 0.0,
            network_io: 0,
            disk_io: 0,
            timestamp: Instant::now(),
        }
    }
    
    fn update(&mut self) {
        // 模拟系统指标更新
        self.cpu_usage = (self.cpu_usage + 0.1) % 100.0;
        self.memory_usage = (self.memory_usage + 0.05) % 100.0;
        self.network_io += 1024;
        self.disk_io += 512;
        self.timestamp = Instant::now();
    }
}

// 线程安全的数据收集器
struct MetricsCollector {
    metrics: Arc<RwLock<Vec<SystemMetrics>>>,
    running: Arc<Mutex<bool>>,
}

impl MetricsCollector {
    fn new() -> Self {
        Self {
            metrics: Arc::new(RwLock::new(Vec::new())),
            running: Arc::new(Mutex::new(false)),
        }
    }
    
    fn start_collection(&self) {
        let metrics = Arc::clone(&self.metrics);
        let running = Arc::clone(&self.running);
        
        thread::spawn(move || {
            *running.lock().unwrap() = true;
            while *running.lock().unwrap() {
                let mut new_metric = SystemMetrics::new();
                new_metric.update();
                
                {
                    let mut metrics_vec = metrics.write().unwrap();
                    metrics_vec.push(new_metric);
                    // 保持最近100个指标
                    if metrics_vec.len() > 100 {
                        metrics_vec.remove(0);
                    }
                }
                
                thread::sleep(Duration::from_millis(100));
            }
        });
    }
    
    fn stop_collection(&self) {
        *self.running.lock().unwrap() = false;
    }
    
    fn get_latest_metrics(&self) -> Option<SystemMetrics> {
        let metrics = self.metrics.read().unwrap();
        metrics.last().cloned()
    }
}

// 高性能并行计算 - 展示Rust的并发能力
fn parallel_computation(data: &[f64]) -> f64 {
    data.par_iter()
        .map(|&x| x * x)
        .sum::<f64>()
        .sqrt()
}

// 异步系统监控
async fn async_system_monitor(collector: &MetricsCollector) {
    println!("🔍 启动异步系统监控...");
    
    for i in 0..10 {
        sleep(Duration::from_millis(500)).await;
        
        if let Some(metrics) = collector.get_latest_metrics() {
            println!("📊 监控周期 {}: CPU={:.1}%, 内存={:.1}%, 网络IO={}KB, 磁盘IO={}KB", 
                i + 1, 
                metrics.cpu_usage, 
                metrics.memory_usage,
                metrics.network_io / 1024,
                metrics.disk_io / 1024
            );
        }
    }
}

// 内存安全演示
fn memory_safety_demo() {
    println!("\n🛡️  内存安全演示");
    println!("==================");
    
    // 创建内存池
    let pool = MemoryPool::new(1024, 10);
    
    // 分配内存块
    if let Some(block_id) = pool.allocate() {
        println!("✅ 成功分配内存块 #{}", block_id);
        
        // 使用内存块
        if let Some(block) = pool.get_block(block_id) {
            println!("📝 内存块大小: {} 字节", block.len());
        }
        
        // 释放内存块 - Rust确保不会出现内存泄漏
        pool.deallocate(block_id);
        println!("♻️  内存块 #{} 已安全释放", block_id);
    }
    
    // 演示所有权转移
    let data = vec![1, 2, 3, 4, 5];
    let moved_data = data; // data的所有权转移
    // println!("{:?}", data); // 编译错误！data已被移动
    println!("📦 数据所有权已转移: {:?}", moved_data);
}

// 并发安全演示
fn concurrency_demo() {
    println!("\n🔄 并发安全演示");
    println!("==================");
    
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    
    // 创建多个线程同时修改共享数据
    for i in 0..5 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            for _ in 0..1000 {
                let mut num = counter.lock().unwrap();
                *num += 1;
            }
            println!("🧵 线程 {} 完成", i);
        });
        handles.push(handle);
    }
    
    // 等待所有线程完成
    for handle in handles {
        handle.join().unwrap();
    }
    
    println!("🔢 最终计数: {}", *counter.lock().unwrap());
}

// 性能优化演示
fn performance_demo() {
    println!("\n⚡ 性能优化演示");
    println!("==================");
    
    // 生成大量数据
    let data: Vec<f64> = (0..1_000_000).map(|i| i as f64).collect();
    
    // 串行计算
    let start = Instant::now();
    let serial_result: f64 = data.iter().map(|&x| x * x).sum::<f64>().sqrt();
    let serial_time = start.elapsed();
    
    // 并行计算
    let start = Instant::now();
    let parallel_result = parallel_computation(&data);
    let parallel_time = start.elapsed();
    
    println!("📈 串行计算时间: {:?}", serial_time);
    println!("📈 并行计算时间: {:?}", parallel_time);
    println!("📈 加速比: {:.2}x", serial_time.as_nanos() as f64 / parallel_time.as_nanos() as f64);
    println!("✅ 结果一致性: {}", (serial_result - parallel_result).abs() < 1e-10);
}

#[tokio::main]
async fn main() {
    println!("🚀 Rust系统级软件特性演示");
    println!("=============================");
    
    // 内存安全演示
    memory_safety_demo();
    
    // 并发安全演示
    concurrency_demo();
    
    // 性能优化演示
    performance_demo();
    
    // 异步系统监控
    println!("\n📡 异步系统监控演示");
    println!("=====================");
    
    let collector = MetricsCollector::new();
    collector.start_collection();
    
    // 运行异步监控
    async_system_monitor(&collector).await;
    
    collector.stop_collection();
    
    println!("\n✨ 演示完成！Rust在系统级编程中的优势：");
    println!("   • 内存安全：零成本的内存管理");
    println!("   • 并发安全：无数据竞争的并发编程");
    println!("   • 性能优化：零成本抽象和并行计算");
    println!("   • 类型安全：编译时错误检查");
    println!("   • 现代特性：async/await异步编程");
}